<?php

namespace App\Admin\Controllers;

use App\Models\UserModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use App\Models\CompanyModel;
use Illuminate\Support\Facades\DB;

class CompanyUserController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '审核公司验证';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new UserModel());

        $grid->model()
            ->where('identity', '=', 2)
            ->where('identity_status','=','2');

        $grid->column('id', __('Id'));
        //$grid->column('account', __('Account'));
       // $grid->column('password', __('Password'));
        $grid->column('nickname','昵称');
        $grid->column('avatar','头像')->image('','200','200');
        $grid->column('name', '姓名');
        //$grid->column('wx_openid', __('Wx openid'));
        $grid->column('phone', '手机号');
        $grid->column('mail', '邮箱');
        //$grid->column('status', __('Status'));
        //$grid->column('identity', __('Identity'));
        //$grid->column('identity_status', __('Identity status'));
        $grid->column('last_used_at','最后登录时间');
        $grid->column('company_id','公司认证')->expand(function ($model) {
           // dd($model->company_id);
            $data = CompanyModel::where('id',$model->company_id)->select([
                'company_name',
                'Invitation_code',
                'max_number',
                'employees_number',
                'industry_type',
                'company_address',
            ])
                ->first()
                ->toArray();

            if(count($data)>0){
                switch ($data['industry_type']){
                    case 1:
                        $data['industry_type'] = '制造业';
                        break;
                    case 2:
                        $data['industry_type'] = '服务业';
                        break;
                    case 3:
                        $data['industry_type'] = '其他';
                        break;
                }
            }
            //转为二位数组
            $new_data[]=$data;

            return new Table(['公司名称', '企业邀请码', '当前小组允许最大人数值','员工人数','行业类型','详细地址'], $new_data);
        });
        $grid->column('Invitation_code', '企业邀请码');

        $grid->column('created_at', '创建时间');
        $grid->column('updated_at', '更新时间');
        $grid->disableCreateButton();
        $grid->disableExport();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(UserModel::findOrFail($id));

        $show->field('id', __('Id'));

        $show->field('nickname','昵称');
        $show->field('avatar','头像')->image('',200,200);
        $show->field('name', '姓名');

        $show->field('phone', '手机号');
        $show->field('mail', '邮箱');

        $show->field('last_used_at','最后登录时间');
        $show->field('company_id','公司认证');
        $show->field('Invitation_code', '企业邀请码');

        $show->company('公司信息', function ($company) {

            $company->setResource('/admin/company-models');

            $company->company_name('公司名称');
            $company->Invitation_code('企业验证码');
            $company->max_number('当前小组允许最大人数值');
            $company->employees_number('员工人数');
            $company->industry_type('行业类型');
            $company->apply_sketch('申请描述');
            $company->province('省');
            $company->city('市');
            $company->district('区/街道');
            $company->company_address('详细地址');
            $company->Industry_description('行业说明');
        });

        $show->field('created_at', '创建时间');
        $show->field('updated_at', '更新时间');


        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new UserModel());

        $form->text('nickname','昵称');
        $form->image('avatar','头像');
        $form->text('name', '姓名');

        $form->mobile('phone', '手机号');
        $form->email('mail', '邮箱');

        $form->datetime('last_used_at','最后登录时间')->default(date('Y-m-d H:i:s'));

        $form->hidden('company_id','公司认证');

        $form->select('identity_status','身份审核')->options([
            2=>'审核中',
            3=>'审核通过',
            4=>'审核不通过'
        ]);

        $form->text('Invitation_code', '企业邀请码')->rules('required|regex:/^\d+$/|min:10', [
            'regex' => 'code必须全部为数字',
            'min'   => 'code不能少于10个字符',
        ])
            ->updateRules(['required', "unique:user,Invitation_code,{{id}}"]);

        $form->text('company_account', '分配企业后台账号')->rules('required|min:6', [
            'required'=>'不能为空',
            'min'   => 'code不能少于6个字符',
        ])
        ->updateRules(['required', "unique:company_users,username,{{id}}"]);

        $form->text('company_password', '分配企业账号后台密码')->rules('required|min:5', [
            'required'=>'不能为空',
            'min'   => 'code不能少于5个字符',
        ]);

        //$form->ignore(['company_account', 'company_password']);
        //保存前回调
        $form->saving(function (Form $form) {
            //dd($_REQUEST);die;  shs_company_users   shs_company_user_permissions shs_company_role_users
            $data = $_REQUEST;
            //插入laravel-admin 企业后台权限控制表
            if($form->identity_status == 3){
                DB::beginTransaction(); //开启事务
                try{
                    $user_id = \DB::table('company_users')->insertGetId([
                        'username'=>$data['company_account'],
                        'password'=> bcrypt($data['company_password']),
                        'name'=> $data['company_account'],
                        'company_id'=> $form->company_id,
                        'created_at'=> date('Y-m-d H:i:s'),
                    ]);
                    \DB::table('company_user_permissions')->insert([
                        'user_id'=>$user_id,
                        'permission_id'=> 1,
                        'created_at'=> date('Y-m-d H:i:s'),
                    ]);
                    \DB::table('company_role_users')->insert([
                        'role_id'=>1,
                        'user_id'=>$user_id,
                        'created_at'=> date('Y-m-d H:i:s'),
                    ]);
                    DB::commit();
                }catch (\Exception $e) {
                    //接收异常处理并回滚
                    $error = new MessageBag([
                        'title'   => '保存错误',
                        'message' => '保存错误.',
                    ]);
                    DB::rollBack();
                    return back()->with(compact('error'));
                }
            }

        });
        return $form;
    }
}
